import fs from "fs";

const {promises} = require('fs');
import {dialog} from "electron";
import * as path from "path";

export const getFeatures = () => {
  const data = fs.readFileSync('resources/features.json', 'utf-8')
  return JSON.parse(data)
}
export const addFeature = (obj) => {
  console.log('obj.name', obj.name)
  console.log('obj.feature', obj.feature)
  const data = fs.readFileSync('resources/features.json', 'utf-8')
  const features = JSON.parse(data)
  console.log('features', features[obj.name])
  let temp = []
  temp = features[obj.name]
  temp.push(obj.feature)
  fs.writeFileSync('resources/features.json', JSON.stringify(features))
}

export async function handleFileOpen() {
  const {canceled, filePaths} = await dialog.showOpenDialog({
    properties: ['openDirectory']
  })
  const directoryPath = filePaths[0]
  if (!canceled) {
    return await getImagesAsBase64(directoryPath)
  }
}

async function getImagesAsBase64(directoryPath) {
  const imageBase64s = [];

  try {
    const files = await promises.readdir(directoryPath);
    for (const file of files) {
      const filePath = path.join(directoryPath, file);
      const ext = path.extname(file).toLowerCase();

      if (ext === '.jpg' || ext === '.jpeg' || ext === '.png') {
        const data = await promises.readFile(filePath);
        imageBase64s.push(`data:image/${ext.slice(1)};base64,${data.toString('base64')}`);
      }
    }

    return imageBase64s;
  } catch (error) {
    console.error('Error getting images as Base64:', error);
    throw error; // 你可以选择重新抛出错误或进行其他错误处理
  }

}
